package everyday;

/**
 * @author 兴趣使然黄小黄
 * @version 1.0
 * @date 2023/6/28 21:30
 * 209. 长度最小的子数组
 * https://leetcode.cn/problems/minimum-size-subarray-sum/
 */
public class Solution209 {

    // 滑动窗口, 时间复杂度O(n)
    public int minSubArrayLen(int target, int[] nums) {
        int n = nums.length;
        int left = 0, right = 0;
        int sum = 0;
        int minLen = Integer.MAX_VALUE;
        while (right < n) {
            // 进入窗口
            sum += nums[right];
            // 判断是否能保存
            while (left <= right &&  sum >= target){
                // 此时已经找到一种结果
                minLen = Math.min((right - left  + 1), minLen);
                // 出窗口
                sum -= nums[left];
                ++left;
            }
            ++right;
        }
        return minLen == Integer.MAX_VALUE ? 0 : minLen;
    }
}
